﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;

namespace StorageManage.Logic
{
    public partial class StorageOut : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string methodName = Request["method"];
            Type type = this.GetType();
            MethodInfo method=type.GetMethod(methodName);
            if (method==null)
            {
                throw new Exception("the method is null");
            }
            try
            {
                method.Invoke(this, null);
            }
            catch (Exception)
            {
                
                throw;
            }
        }
        public void GetStorageOutList()
        {
            List<SearchCondition> listSearch = new List<SearchCondition>();
            if (Request.Form["searchData"] != null)
            {
                string searchData = Request.Form["searchData"];
                listSearch = ModelTools.GetSearchContions(searchData);
                if (listSearch.Where(o => o.Field == "StartTime").FirstOrDefault() != null)
                {
                    listSearch.Where(o => o.Field == "StartTime").FirstOrDefault().Field = "ApplyTime";
                }
                if (listSearch.Where(o => o.Field == "EndTime").FirstOrDefault() != null)
                {
                    listSearch.Where(o => o.Field == "EndTime").FirstOrDefault().Field = "ApplyTime";
                }
            }
            string OrderId = OperateContext.Sort == null ? "Id" : OperateContext.Sort;
            Expression<Func<View_StorgaeOut, bool>> exp = SearchExpression.FindByGroup<View_StorgaeOut>(listSearch);
            var list = DALSession.Current.View_StorgaeOutDAL.GetPagedList(OperateContext.Page, OperateContext.Rows, exp, OrderId, OperateContext.OrderDesc);
            int count = DALSession.Current.View_StorgaeOutDAL.GetCount(exp);
            Response.Write(JsonHelper.toPageJson(list, count));
        }
        public void GetStorageOutDetial()
        {
            string[] ids=Request.QueryString["ids"].Trim(',').Split(',');
            List<int> idList = new List<int>();
            for (int i = 0; i < ids.Length; i++)
            {
                idList.Add(Commons.String2Int32(ids[i]));
            }
            var storageList=DALSession.Current.View_StorageDAL.GetListBy(o => idList.Contains(o.Id));
            List<View_StorgaeOut> outList = new List<View_StorgaeOut>();
            storageList.ForEach(o=>{
                View_StorgaeOut outDetail = new View_StorgaeOut() { 
                    MaterialCode=o.MaterialCode,
                    Name=o.Name,
                    Guige=o.Guige,
                    Caizhi=o.Caizhi,
                    Mweight=o.Mweight,
                    CunHuoZhangNum=o.ZhangNum,
                    CunHuoWeight=o.TotalWeight,
                    OutZhangNum=o.ZhangNum,
                    OutTotalWeight=o.TotalWeight,
                    OutGuid=o.Guid,
                    Length=o.Length,
                    Width=o.Width,
                    MaterialType=o.MaterialType,
                };
                outList.Add(outDetail);
               
            });
            StorageManage.StorageOut outMain = new StorageManage.StorageOut();
            outMain.OutCode = GenerateOutNum();
            outMain.TaskCode = storageList.FirstOrDefault().TaskCode;
            outMain.ProjName = storageList.FirstOrDefault().ProjName;
            outMain.EngName = storageList.FirstOrDefault().EngName;
            outMain.Warehouse = storageList.FirstOrDefault().Warehouse;
            outMain.ApplyPerson = OperateContext.UserInfo.UserName;
            outMain.ApplyTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            Response.Write(JsonHelper.toJson(new { outList = outList, outMain = outMain }));
        }
        public void GetStorageOutDetial1() {
            string outCode=Request.QueryString["outCode"];
            StorageManage.StorageOut outMain=DALSession.Current.StorageOutDAL.GetListBy(o => o.OutCode == outCode).FirstOrDefault();
            var outList=DALSession.Current.View_StorgaeOutDAL.GetListBy(o => o.OutCode == outCode);
            Response.Write(JsonHelper.toJson(new { outList = outList, outMain = outMain }));
        }
        public string GenerateOutNum()
        {
            string outCode = "";
            var list=DALSession.Current.StorageOutDAL.GetListBy(o=>true);
            if (list==null ||list.Count==0)
            {
                outCode = "CK00000001";
            }
            else
            {
                string code=list.LastOrDefault().OutCode;
                outCode="CK"+(Commons.String2Int32(code.Substring(2))+1).ToString().PadLeft(8,'0');
            }
            return outCode;
        }
        public void AddStorageOut()
        {
            StorageManage.StorageOut sm=new StorageManage.StorageOut();
            ModelTools.Form2Model(Request.Form,sm);
            var outList = JsonConvert.DeserializeObject<List<StorageOutDetail>>(Request.Form["info"]);
            int id=Commons.String2Int32(DALSession.Current.StorageOutDAL.AddModelReturnId(sm));
            outList.ForEach(o =>
            {
                var store = DALSession.Current.StorageDAL.GetListBy(s => s.Guid == o.OutGuid).FirstOrDefault();
                o.MainId = id;
                o.CunHuoWeight = store.TotalWeight ;
                o.CunHuoZhangNum = store.ZhangNum;
                DALSession.Current.StorageOutDetailDAL.Add(o);
                store.TotalWeight = store.TotalWeight-o.OutTotalWeight;
                store.ZhangNum = store.ZhangNum - o.OutZhangNum;
                
                if (store.TotalWeight!=0)
                {
                    DALSession.Current.StorageDAL.ModifyAllModel(store);
                }
                else
                {
                    DALSession.Current.StorageDAL.Del(store);
                }
                
            });
            DALSession.Current.StorageDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true, "保存成功"));
            
            
        }
        public void EditStorageOut()
        {
            //修改出库总表
            string outCode=Request.Form["OutCode"];
            var sm=DALSession.Current.StorageOutDAL.GetListBy(o=>o.OutCode==outCode).FirstOrDefault();
            ModelTools.Form2Model(Request.Form, sm);
            DALSession.Current.StorageOutDAL.ModifyAllModel(sm);

            
            var outList = JsonConvert.DeserializeObject<List<StorageOutDetail>>(Request.Form["info"]);
            //恢复库存数据
            var oldDetailList=DALSession.Current.View_StorgaeOutDAL.GetListBy(o => o.MainId == sm.Id);
            oldDetailList.ForEach(o=>{
                var oldStorage=DALSession.Current.StorageDAL.GetListBy(s => s.Guid == o.OutGuid).FirstOrDefault();
                if (oldStorage==null)
                {

                    var storageIn=DALSession.Current.View_StorageInDAL.GetListBy(s => s.InGuid == o.OutGuid).FirstOrDefault();                   
                    var store = DALSession.Current.StorageDAL.GetListBy(s => s.Guid == o.OutGuid).FirstOrDefault();
                    Storage storage = new Storage();
                    
                    storage.TaskCode = o.TaskCode;
                    storage.ProjName = o.ProjName;
                    storage.EngName = o.EngName;
                    storage.Guid = o.OutGuid;
                    storage.MaterialCode = o.MaterialCode;
                    storage.Length = o.Length;
                    storage.Width = o.Width;
                    storage.ZhangNum = o.OutZhangNum;
                    storage.TotalWeight = o.OutTotalWeight;
                    if (storageIn==null)
                    {
                        storage.MaterialType = "";
                        storage.Warehouse = "";
                        storage.InCode = "";
                    }
                    else
                    {
                        storage.MaterialType = storageIn.MaterialType;
                        storage.Warehouse = storageIn.Warehouse;
                        storage.InCode = storageIn.InCode;
                    }
                    
                    DALSession.Current.StorageDAL.Add(storage);
                }
                else
                {
                    oldStorage.ZhangNum = o.OutZhangNum + oldStorage.ZhangNum;
                    oldStorage.TotalWeight = o.OutTotalWeight + oldStorage.TotalWeight;
                    DALSession.Current.StorageDAL.ModifyAllModel(oldStorage);
                }
                

            });
            //删除对应出库单里面的所有明细
            DALSession.Current.StorageOutDetailDAL.DelBy(o => o.MainId==sm.Id);
            DALSession.Current.StorageDAL.SaveChanges();
            //重新添加出库单明细
            outList.ForEach(o =>
            {
                var store = DALSession.Current.StorageDAL.GetListBy(s => s.Guid == o.OutGuid).FirstOrDefault();
                o.MainId = sm.Id;
                o.CunHuoWeight = store.TotalWeight;
                o.CunHuoZhangNum = store.ZhangNum;
                DALSession.Current.StorageOutDetailDAL.Add(o);
                
                store.ZhangNum = store.ZhangNum - o.OutZhangNum;
                store.TotalWeight = store.TotalWeight-o.OutTotalWeight;
                if (store.TotalWeight != 0)
                {
                    DALSession.Current.StorageDAL.ModifyAllModel(store);
                }
                else
                {
                    DALSession.Current.StorageDAL.Del(store);
                }

            });
            DALSession.Current.StorageDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true, "保存成功"));
        }
        public void InsertStorageOut()
        {
            string outCode=Request.QueryString["outCode"];
            var outmain=DALSession.Current.StorageOutDAL.GetListBy(o=>o.OutCode==outCode).FirstOrDefault();
            var storageList=JsonConvert.DeserializeObject<List<StorageManage.Storage>>(Request.Form["info"]);  
            storageList.ForEach(o=>{
                StorageOutDetail detail = new StorageOutDetail();
                detail.MainId = outmain.Id;
                detail.Length = o.Length;
                detail.Width = o.Width;
                detail.OutTotalWeight = 0;
                detail.OutZhangNum = 0;
                detail.CunHuoZhangNum = o.ZhangNum;
                detail.CunHuoWeight = o.TotalWeight;
                detail.MaterialCode = o.MaterialCode;
                detail.OutGuid = o.Guid;
                DALSession.Current.StorageOutDetailDAL.Add(detail);
            });
            DALSession.Current.StorageOutDetailDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true));
        }
        public void GetViewStorageOut()
        {
            string outCode=Request.QueryString["outCode"];
            var list=DALSession.Current.View_StorgaeOutDAL.GetListBy(o => o.OutCode == outCode);
            var main = DALSession.Current.StorageOutDAL.GetListBy(o => o.OutCode == outCode).FirstOrDefault();
            Response.Write(JsonHelper.toJson(new { list = list, main = main }));

        }
        public void DeteleStorageOut()
        {
            int id =Commons.String2Int32(Request.QueryString["id"]);
            //恢复库存
            var outList=DALSession.Current.View_StorgaeOutDAL.GetListBy(o => o.MainId==id);
            outList.ForEach(o=>{
                var oldStorage = DALSession.Current.StorageDAL.GetListBy(s => s.Guid == o.OutGuid).FirstOrDefault();
                if (oldStorage == null)
                {
                    var storageIn = DALSession.Current.View_StorageInDAL.GetListBy(s => s.InGuid == o.OutGuid).FirstOrDefault();
                    
                    Storage storage = new Storage();
                    
                    storage.TaskCode = o.TaskCode;
                    storage.ProjName = o.ProjName;
                    storage.EngName = o.EngName;
                    storage.Guid = o.OutGuid;
                    storage.MaterialCode = o.MaterialCode;
                    storage.Length = o.Length;
                    storage.Width = o.Width;
                    storage.ZhangNum = o.OutZhangNum;
                    storage.TotalWeight = o.OutTotalWeight;


                    if (storageIn != null)
                    {
                        storage.InCode = storageIn.InCode;
                        storage.MaterialType = storageIn.MaterialType;
                        storage.Warehouse = storageIn.Warehouse;
                    }
                    DALSession.Current.StorageDAL.Add(storage);
                }
                else
                {
                    oldStorage.ZhangNum = o.OutZhangNum + oldStorage.ZhangNum;
                    oldStorage.TotalWeight = o.OutTotalWeight + oldStorage.TotalWeight;
                    DALSession.Current.StorageDAL.ModifyAllModel(oldStorage);
                }
            });
            //删除出库单
            DALSession.Current.StorageOutDetailDAL.DelBy(o => o.MainId == id);
            DALSession.Current.StorageOutDAL.DelBy(o => o.Id == id);
            DALSession.Current.StorageOutDAL.SaveChanges();

            Response.Write(JsonHelper.toDefaultMsg(true));
        }
       
    }
    
}